const HOST = "127.0.0.1";
const PORT = 30000;
const JSON_DIR = "data";
const WebApi = "/webapp/mobile";

const createError = require("http-errors");
const express = require("express");
const bodyParser = require("body-parser");
const fs = require("fs");
const logger = require("morgan");
const cors = require("cors");


const app = express();
app.use(bodyParser.json());

// 跨域
app.use(cors());

// 日志
app.use(logger("dev"));


// 自动生成接口
const files = fs.readdirSync(JSON_DIR).filter(item=>item.endsWith('.json'));
for (let i = 0; i < files.length; i++) {
  const url = WebApi + "/" + files[i].replace(/_/g, "/").replace(/\.json/g, "");

  // get请求
  app.get(url, function (req, res) {
    fs.readFile(`./${JSON_DIR}/${files[i]}`, "utf-8", function (err, data) {
      if (err) {
        console.error(err);
        res.status(500).send({
          message: err.message || "Error occurred when retrieving users",
        });
      } else {
        res.send(data);
      }
    });
  });

  // post请求
  app.post(url, function (req, res, next) {
    fs.readFile(`./${JSON_DIR}/${files[i]}`, "utf-8", function (err, data) {
      if (err) {
        console.error(err);
        res.status(500).send({
          message: err.message || "Error occurred when retrieving users",
        });
      } else {
        res.send(data);
      }
    });
  });
}

// 首页-接口列表
app.get("/", (req, res) => {
  var html =
    `<h3>接口列表：</h3>` +
    files
      .map((file) => {
        const url =
          `http://${HOST}:${PORT}` +
          WebApi +
          "/" +
          file.replace(/_/g, "/").replace(/\.json/g, "");
        return `<p><a href="${url}">${url}</a></p>`;
      })
      .join("");
  res.send(html);
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

app.listen(PORT, () => {
  console.log(`服务启动：http://${HOST}:${PORT}`);
});
